package dawn.util;

import java.util.Collection;

/**
 * 随机奖励算法
 * @author huangxiao
 */
public class RandomReward {

	/**
	 * 从列表中随机获得一个物品
	 * @param list 物品列表，容器中的元素需要是IWeight的子类
	 * @return 随机的结果
	 */
	public static IWeight random(Collection<? extends IWeight> list) {
		IWeight ret = null;
		int s1 = 0;
		for (IWeight t : list) {
			s1 += t.getWeight();
		}

		int random = (int) (s1 * Math.random());

		int sum = 0;
		for (IWeight t : list) {
			sum += t.getWeight();

			if (random < sum) {
				ret = t;
				break;
			}
		}
		return ret;
	}

	/**
	 * 从列表中随机获得一个物品
	 * @param list 物品列表
	 * @param accessor 通过访问器来获得每个物品的权重
	 * @return 随机的结果
	 */
	public static <T> T random(Collection<T> list, IWeightAccessor<T> accessor) {
		T ret = null;
		int s1 = 0;
		for (T t : list) {
			s1 += accessor.getWeight(t);
		}

		int random = (int) (s1 * Math.random());

		int sum = 0;
		for (T t : list) {
			sum += accessor.getWeight(t);

			if (random < sum) {
				ret = t;
				break;
			}
		}
		return ret;
	}

	/**
	 * 权重接口
	 * @author huangxiao
	 *
	 */
	public static interface IWeight {
		int getWeight();
	}

	/**
	 * 权重访问结口
	 * @author huangxiao
	 *
	 * @param <T>
	 */
	public static interface IWeightAccessor<T> {
		int getWeight(T t);
	}
}
